import { ChangeDetectionStrategy, Component, OnInit, Pipe, PipeTransform, ViewChild } from '@angular/core';
import { SortDirective, TreetableComponent, TreeTableNode } from '@iux/live';
import { TreetableService } from '../tree-table.service';
import { forEach, map, result } from 'lodash';

@Pipe({ name: 'userProp' })
export class UserPropPipe implements PipeTransform {
  transform(value: TreeTableNode[], exponent: string = 'data.name') {
    return map(value, item => result(item, exponent)).join(',');
  }
}

@Component({
  selector: 'app-checkbox-selection',
  templateUrl: './checkbox-selection.component.html',
  styles: [
    `
      p {
        margin: 16px 0;
      }
      p button:not(:last-child) {
        margin-right: 16px;
      }
      lv-paginator {
        margin-top: 16px;
      }
    `,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CheckboxSelectionComponent implements OnInit {
  data: TreeTableNode[];
  selection: TreeTableNode[];
  @ViewChild(TreetableComponent, { static: false }) lvTable: TreetableComponent;
  @ViewChild(SortDirective, { static: false }) lvSort: SortDirective;

  constructor(private treetableService: TreetableService) {}

  ngOnInit() {
    this.initData();
  }

  initData() {
    this.treetableService.getUsers().subscribe((res: TreeTableNode[]) => {
      this.data = res;
      this.selection = [];
      this.initSelection(this.data[0]);
    });
  }

  // 默认选中第一个节点及其子节点
  initSelection(source) {
    this.selection.push(source);
    forEach(source.children, item => {
      !item.disabled && this.initSelection(item);
    });
  }

  selectionChange(source) {
    console.log('selection change', source);
  }

  updateData() {
    this.initData();
    this.lvSort.clear();
  }

  clearSelection() {
    this.lvTable.clearSelection();
  }

  stateChange(source: { [key: string]: any }) {
    console.log('state change:', source);
  }
}
